// components/commentItem/commentItem.js
Component({
  lifetimes: {
    attached: function(){
      console.log("attached data=", this.data)
      let fid = this.data.comment._id //父评论id
      const collection = wx.cloud.database().collection('comments')
      collection.where({
        parentId: fid
      }).count().then(res => {
        console.log('子评论条数', res.total)
        let total = res.total
        this.setData({subCommentsCount: total})
        if(total != 0){
          collection.where({
            parentId: fid
          }).field({
            content: true, username: true
          }).limit(2).get().then(res => {
            console.log('子评论前2', res)
            this.setData({subComments: this.data.subComments.concat(res.data)})
          }).catch(err => {
            console.log(err)
          })
        }
      })
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    comment:{
      type: Object,
      value:{}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    subComments: [],
    subCommentsCount: 0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    _reply: function(e){
      console.log('点击父评论, e=',e)
      this.triggerEvent('reply', {fid: e.currentTarget.dataset['fid']})
    },
    _showMoreSubComments: function(){
      let fid = this.data.comment._id //父评论id
      wx.cloud.database().collection('comments').where({
        parentId: fid
      }).field({
        content: true, username: true
      }).skip(this.data.subComments.length).limit(20).get().then(res => {
        console.log('子评论前2', res)
        this.setData({subComments: this.data.subComments.concat(res.data)})
      }).catch(err => {
        console.log(err)
      })
    },
    _addOneSubComment: function(id, username, content){
      this.setData({
        subComments: this.data.subComments.concat([{_id: id, content: content, username: username}]), 
        subCommentsCount: this.data.subCommentsCount + 1
      }, 
      console.log('子评论添加完成后', this.data, '子评论数据列表', this.data.subComments, '总数为', this.data.subCommentsCount))
    }
  }
})
